<template>
	<el-container v-if="isAlready">
		<el-header>
			<div class="left-panel">
				<fsButton ref="button" plain size="small" :buttons="buttons" @clickHandler="buttonHandler"></fsButton>
			</div>
			<div class="right-panel">
				<ex-search ref="search" :searches="searches" @searchOk="searchHandler" default-code="changeAfter.code" placeholder="请输入资产编码" :fixedParam="fixedParams" :initParams="searchParams"></ex-search>
			</div>
		</el-header>
		<el-main class="nopadding" style="padding: 0 10px;">
			<div class="DueTableTop">
					<div style="height: 100%;width: 100%;margin-bottom: -10px;height: 44px;">
						<div style="margin-left: 15px;float: left;margin-top: 6px;">
							<img class="cardtopblockimg" src="img/technolg.png"/>
						</div>
						<div style="float: left;font-size: 14px;font-weight: 400;margin-left: 20px;
						color: rgb(72, 74, 77);line-height: 44px;">
							<p>{{title}}</p>
						</div>
					</div>
				</div>
			<el-table ref="table" :data="tableDatas"
					  row-key="id"
					  :key="elKey"
					  :height="this.tableHeight"
					  :border=true
					  :stripe=true v-loading="loading">
				<el-table-column type="expand">
					<template #default="props">
						<div style="min-height: 30px;width: 41%;padding-left: 105px;">
							<ex-table :columns="assetLogColumns" size="small" :height="0" hide-on-single-page :selection="false" :url="this.$API.asset.assetLog.list.url" :params="Object.assign({assetId:props.row.id},this.exSearchParams)" @columnClick="columnClickHandler"></ex-table>
						</div>
					</template>
				</el-table-column>
				<template v-for="column in this.assetColumns" :key="column.code">
					<el-table-column :prop="column.code"
									 :label="column.name"
									 :sortable="column.sortable?column.sortable:false"
									 :formatter="this.formatters"
									 :column-key="column.code"
									 :summary = "column.summary? column.summary:false"
									 :show-overflow-tooltip="true"
									 :width="column.width?column.width:null">
					</el-table-column>
				</template>
			</el-table>
			<el-pagination ref="pagination"
						   v-model:current-page="pageForm.current"
						   v-model:page-size="pageForm.pageSize"
						   :page-sizes="[30,50,100]"
						   :small="true"
						   :hide-on-single-page="false"
						   background
						   layout="->,total, jumper, sizes, prev, pager, next"
						   :total="total"
						   @size-change="handleSizeChange"
						   @current-change="handleCurrentChange"
						   style="margin: 0 0 0 0;padding: 8px 0px;">
			</el-pagination>
		</el-main>
	</el-container>
	<data-card ref="dataCard"></data-card>
</template>

<script>
import ExTable from "@/components/exTable/index.vue";
import ExSearch from "@/components/exSearch/index.vue";
import tool from "@/utils/tool";
import DataCard from "@/views/asset/card/card.vue";
import useTabs from "@/utils/useTabs";
import {h} from "vue";
import {ElButton, ElContainer} from "element-plus";
import router from '@/router'
import BaseTemplate from "@/utils/baseTemplate";
export default {
	name: '资产履历查询',
	computed: {
		tool() {
			return tool
		}
	},
	components: {
		DataCard,
		ExSearch,
		ExTable,
	},
	data() {
		return {
			dialog: {
				save: false,
				permission: false,
			},
			apiObj: [],
			buttons: [
				{name: "导出", icon: "el-icon-download", click: "export", type: "info", permission: "export"},
			],
			searches: [
				{type: "tree-select", name: "管理部门", code: "dutyDepartmentIds", placeholder: "请选择管理部门", dictCode:'SysOrganization',checkStrictly:false,multiple:true},
				{type: "tree-select", name: "操作类型", code: "processTypeIds", placeholder: "请选择操作类型", dictCode:'FamsDocumentProcessType',checkStrictly:false,multiple:true},
				{type: "input", name: "资产编码", code: "changeAfter.code", placeholder: "请输入资产编码", maxlength: 30, showLimit: true},
				{type: "tree-select", name: "资产分类", code: "assetCategoryIds", placeholder: "请选择资产分类", dictCode:'FamsAssetCategory',checkStrictly:false,multiple:true,dataPermissionProcess:true},
				{type: "select", name: "资产状态", code: "assetStatusIds", placeholder: "请选择资产状态", dictCode:'ASSET_STATUS',multiple:true},
				{type: "tree-select", name: "使用部门", code: "usingDepartmentIds", placeholder: "请选择使用部门", dictCode:'SysOrganization',checkStrictly:false,multiple:true,dataPermissionProcess:true,permissionData:this.$TOOL.current.readDeptIds()},
				{type: "selector", name: "使用人", code: "changeAfter.usingMenId", placeholder: "请选择使用人", dictCode:'SysUser'},
				{type: "daterange", name: "操作日期", code: "createTimeStart,createTimeEnd", placeholder: "请选择操作日期", formatter:"YYYY-MM-dd",valueFormat:"YYYYMMDD",range:365},
				{type: "daterange", name: "购置日期", code: "boughtDateStart,boughtDateEnd", placeholder: "请选择购置日期", formatter:"YYYY-MM-dd",valueFormat:"YYYYMMDD",range:365},
				{type: "daterange", name: "维修完成日期", code: "zcbxFinishDateStart,zcbxFinishDateEnd", placeholder: "请选择维修完成日期", formatter:"YYYY-MM-dd",valueFormat:"YYYYMMDD",range:365},
				{type: "daterange", name: "调拨日期", code: "zcdbDateStart,zcdbDateEnd", placeholder: "请选择调拨日期", formatter:"YYYY-MM-dd",valueFormat:"YYYYMMDD",range:365},
				{type: "daterange", name: "转移日期", code: "zczyDateStart,zczyDateEnd", placeholder: "请选择转移日期", formatter:"YYYY-MM-dd",valueFormat:"YYYYMMDD",range:365},
				{type: "daterange", name: "报废日期", code: "scrapDateStart,scrapDateEnd", placeholder: "请选择报废日期", formatter:"YYYY-MM-dd",valueFormat:"YYYYMMDD",range:365},
				{type: "daterange", name: "领用日期", code: "recipientOnDateStart,recipientOnDateEnd", placeholder: "请选择领用日期", formatter:"YYYY-MM-dd",valueFormat:"YYYYMMDD",range:365},
			],
			assetColumns: [
				{code: "assetStatusId", name: "资产状态", width:"65",formatter:"DICT",key: "ASSET_STATUS"},
				{code: "code", name: "资产编码", width:"135",click:"show1"},
				{code: "financialCode", name: "财务编码", width:"170"},
				{code: "name", name: "资产名称", width:"200"},
				{code: "assetCategoryId", name: "资产分类",width:"180", formatter:"DICT",key: "FamsAssetCategory"},
				{code: "storePlaceId", name: "资产位置",width: "120", formatter:"DICT",key: "FamsPosition"},
				{code: "other.financialBarCode", name: "财务条形码", width:"100"},
				{code: "other.purchaseOrderCode", name: "申购单号", width:"100"},
				{code: "brand", name: "品牌", width:""},
				{code: "model", name: "规格型号", width:""},
				{code: "serialCode", name: "资产序列号", width:"150"},
				{code: "assetCount", name: "数量", width:"50",summary:true},
				{code: "originalValue", name: "资产原值", width:"100",summary:true},
				{code: "netValue", name: "资产净值", width:"100",summary:true},
				{code: "usingMenId", name: "使用人", width:"110",formatter: "DICT",key: "SysUser"},
				{code: "usingDepartmentId", name: "使用部门", width:"150",formatter: "DICT",key: "SysOrganization"},
				{code: "dutyDepartmentId", name: "管理部门", width:"150",formatter: "DICT",key: "SysOrganization"},
				{code: "boughtDate", name: "购置日期", width:"110",formatter: "DATE"},
				{code: "recipientOnDate", name: "领用日期", width:"110",formatter: "DATE"},
			],
			assetLogColumns: [
				{code: "documentInfo.code", name: "单据编号", width:"140",click:"toDocument"},
				{code: "documentInfo.status", name: "单据状态", width:"95",formatter:"DICT",key: "DOCUMENT_STATUS"},
				{code: "documentInfo.createUser", name: "操作人", width:"110",formatter: "DICT",key: "SysUser"},
				{code: "documentInfo.processTypeId", name: "处理方式", width:"100",formatter:"DICT",key: "FamsDocumentProcessType"},
				// {code: "changeInfo", name: "操作内容", width:"",formatter: 'CHANGE_INFO'},
				{code: "documentInfo.createTime", name: "操作日期", width:"110",formatter: "DATE"},
				{code: "documentInfo.documentConfigId", name: "单据类型", width:"100",formatter:"DICT",key: "FamsDocumentConfig"},
				{code: "详细", name: "详细", width:"",fixedValue:"详细",click:"toAsset"},
			],
			elKey: 0,
			parentLevelCode:"",
			assetIds:[],
			loading: false,
			isAlready:false,
			pageForm: {
				current: 1,
				pageSize: 30,
			},
			tableHeight:0,
			total: 0,
			tableDatas: [],
			excludeStatus:['delete'],
			formatLabels:{},
			loginUsers: tool.current.user(),
			searchParams:{},
			exSearchParams:{},
			fixedParams:{},
			deptIds:this.$TOOL.current.readDeptIds(),
			assetCategoryIds:this.$TOOL.current.manageAssetCategoryIds(),
			title:"查询资产履历"

		}
	},
	created() {
		//如果是通过跳转过来的，标签的名称设置为跳转后的标题
		let route = router.currentRoute.value;
		if(route.meta){
			this.title=route.meta.title;
		}
		let routeParams = this.$store.state.routeParams[this.$route.params.key];
		if(routeParams){
			if(routeParams.title){
				useTabs.setTitle(routeParams.title);
				document.title = routeParams.title;
			}
			this.buttons = [
				{name: "导出", icon: "el-icon-download", click: "export", type: "info"},
			]
			if (routeParams.fixedParams) {
				Object.assign(this.fixedParams,routeParams.fixedParams);
				if(routeParams.fixedParams.deptIds){
					this.deptIds = routeParams.fixedParams.deptIds;
				}
				if(routeParams.fixedParams.assetCategoryIds){
					this.assetCategoryIds = routeParams.fixedParams.assetCategoryIds;
				}
			}
			if (routeParams.searchParams) {
				Object.assign(this.searchParams,routeParams.searchParams);
			}
		}
		this.isAlready = true;
	},
	mounted() {
		this.resetTableHeight();
		window.addEventListener("resize", this.resetTableHeight);
		this.searchHandler();
	},
	beforeMount() {
	},
	beforeUnmount() {
		window.removeEventListener("resize", this.resetTableHeight);
	},
	methods: {
		resetTableHeight() {
			let height = this.$refs.table.$parent.$el.clientHeight - 40-56;
			if (height <= 300) {
				this.tableHeight = 300;
			} else {
				this.tableHeight = height;
			}
			if(!this.tableHeight){
				this.tableHeight = 200;
			}
		},
		buttonHandler(index, name) {
			this.$options.methods[name](this, index);
		},
		async searchHandler() {
			let queryParams = this.$refs.search.searchParams();
			this.exSearchParams = tool.objCopy(queryParams);
			this.loading = true;
			//释放搜索组件的loading状态
			if (this.$refs.search) {
				this.$refs.search.setLoading(true);
			}
			queryParams.excludeStatus = this.excludeStatus;
			queryParams = Object.assign(queryParams, this.pageForm);
			this.$API.asset.assetLog.getFamsAssetPage.post(queryParams).then((rsp =>{
				if(rsp.code === 2000){
					this.setTableData(rsp.data);
				}else{
					this.loading = false;
				}
			}));
		},
		async setTableData(data) {
			this.pageForm.current = data.current;
			this.pageForm.pageSize = data.size;
			this.total = data.total;
			let oriRecords = data.records || data; //支持分页和不分页
			if (oriRecords.length === 0) {
				this.tableDatas = oriRecords;
				this.elKey++;
				this.loading = false;
				if (this.$refs.search) {
					this.$refs.search.setLoading(false);
				}
				return;
			}
			this.assetColumns.forEach(column=>{
				if (!column.property) {
					column.property = column.code;
				}
				column["_processFinish"] = 0;
			});
			let formatLimitCount = oriRecords.length;

			for (let column of this.assetColumns) {
				if (column.formatter === 'DICT') {
					for (let row of oriRecords) {
						if (column["_processFinish"] < formatLimitCount) {
							let value = this.getValue(column.property, row);
							let formatKey = column.key + "_" + value;
							row["_" + column.property] = formatKey;
							if (this.formatLabels[formatKey]) {
								column["_processFinish"] = column["_processFinish"] + 1;
								this.setRealTableData(oriRecords, formatLimitCount);
							} else {
								let label = await this.$cache.dic.label(column.key, value, true);
								let formatLabel = label;
								/* 去掉颜色
								if (label && !label.type) {
									formatLabel = h(ElTag, {
										size: 'small',
										style: "color:#409effF2;background-color: #409eff0D;border: #409eff"
									}, {default: () => label});
								}
								*/
								//缓存已处理格式化内容
								this.formatLabels[formatKey] = formatLabel;
								column["_processFinish"] = column["_processFinish"] + 1;
								this.setRealTableData(oriRecords, formatLimitCount);
							}
						}
					}
				} else {
					column["_processFinish"] = formatLimitCount;
					this.setRealTableData(oriRecords, formatLimitCount);
				}
			}
		},
		setRealTableData(processData, formatLimitCount) {
			if (this.assetColumns.filter(item => item["_processFinish"] !== formatLimitCount).length === 0) {
				this.tableDatas = processData;
				this.loading = false;
				this.elKey++;
				//释放搜索组件的loading状态
				if (this.$refs.search) {
					this.$refs.search.setLoading(false);
				}
				this.$nextTick(() => {
					if (this.$refs.table) {
						this.$refs.table.doLayout();
					}
				});
			}
		},
		getValue(property, row) {
			let nodes = property.split(".");
			let objValue = null;
			for (const node of nodes) {
				let tempValue = null;
				if (objValue) {
					tempValue = objValue[node];
				} else {
					tempValue = row[node];
				}
				if (typeof tempValue !== "object") {
					return tempValue;
				} else {
					objValue = tempValue;
				}
			}
			return null;
		},
		columnClickHandler(name,data){
			this.$options.methods[name](this, data);
		},
		//查看
		async show1(_this, row) {
			let assetCategory = await _this.$cache.data.loadAssetCategory(row.assetCategoryId);
			try {
				_this.loading = true;
				let entity = {cardId: assetCategory.assetCardId, _editFlag: false}
				_this.$nextTick(() => {
					_this.cardPreview = false;
					_this.$refs.dataCard.open(Object.assign(entity, row));
				});
			} finally {
				_this.loading = false;
			}
		},
		//导出
		async export(_this,index) {
      let attachParams = _this.$refs.search.searchParams();
      let exportApi = _this.$API.asset.assetLog.export;
      let exTableRef = null;
      let exportBtnRef = _this.$refs.button;
      let exportBtnIndex = index;
      await BaseTemplate.export(_this, exportApi, attachParams, exportBtnRef, exportBtnIndex, exTableRef);
		},
		toDocument(_this,row){
			_this.$nextTick(() => {
				_this.$router.push({name:"documentPrepare",params:{fromRouteId:_this.$TOOL.crypto.MD5(_this.$route.path),configId:row.documentInfo.documentConfigId,id:row.documentId}});
			})
		},
		async toAsset(_this, row) {
			try {
				_this.loading = true;
				_this.dataCardShow = true;
				let rsp = await _this.$API.asset.document.findById.post({id: row.documentId});
				if (rsp.code === 2000) {
					let document = rsp.data;
					let entity = {modelId: row.documentId, cardId: document.processType.showCardId, _editFlag: false}
					if(row.documentDetailId){
						let res = await _this.$API.asset.documentDetail.findById.post({id: row.documentDetailId});
						if (res.code === 2000) {
							_this.$nextTick(() => {
								_this.$refs.dataCard.open(Object.assign(entity, res.data));
							});
						}
					}
				}

			} finally {
				_this.loading = false;
			}
		},
		handleSizeChange(pageSize) {
			this.pageForm.pageSize = pageSize;
			this.searchHandler();
		},
		handleCurrentChange(currentPage) {
			this.pageForm.current = currentPage;
			this.searchHandler();
		},
		formatters(row, column, cellValue, index) {
			for (const item of this.assetColumns) {
				if (item.code === column.property){
					if (item.click) {
						if (item.fixedValue) {
							cellValue = item.fixedValue;
						} else {
							if (item.formatter) {
								if (item.formatter instanceof Function) {
									cellValue = item.formatter(row, cellValue, this);
								} else {
									cellValue = tool.format.convert(cellValue, item.formatter, item.key);
								}
							}
						}
						let label = cellValue+'';
						let clicks = item.click.split(',');
						let labels = label.split(',');
						let permissions = [];
						if (item.permissions) {
							permissions = item.permissions.split(',');
							// permissions.splice(permissions.indexOf(''), 1);
						}
						let children = [];
						clicks.forEach((click, index) => {
							let elBtn = h(ElButton, {
								link: true,
								type: 'primary',
								style: {margin: 'auto'},
								size: 'small',
								["onClick"]: () => {
									this.$options.methods[click](this, row);
									// this.$emit('columnClick', click, row);
								}
							}, () => labels[index])
							if (permissions.length > 0) {
								if (permissions.filter(item => item === click).length > 0) {
									children.push(elBtn);
								}
							} else {
								children.push(elBtn);
							}
						});
						// cellValue = h(ElButton,{link:true,type:'primary',size:'small',["onClick"]:()=>{ this.$emit('columnClick',item.click,row);}},()=>label);
						cellValue = h(ElContainer, {key: tool.uuid("elk"), style: {display: 'flex'}}, () => children);
					}else{
						if (item.formatter) {
							if (item.formatter) {
								if (item.formatter instanceof Function) {
									cellValue = item.formatter(row, cellValue, this);
								} else if (row["_" + item.property]) {
									cellValue = this.formatLabels[row["_" + item.property]];
								} else {
									cellValue = tool.format.convert(cellValue, item.formatter, item.key);
								}
							}
						}
					}
				}

			}
			return cellValue;
		},
	}
}

</script>
